import { defineStore } from "pinia";
import {login, register} from '../api/auth'

interface UserState {
    token: string | null
    userInfo: object | null
}
interface LoginForm {
  username: string
  password: string
}

interface RegisterForm extends LoginForm {
  email: string
}


export const useUserStore = defineStore("user", {
    state: (): UserState => ({
        token: localStorage.getItem('token'),
        userInfo: null
      }),
      getters: {
        isAuthenticated: (state) => !!state.token
      },
      actions: {
        async login(form: LoginForm) {
          try{
            // const response = await request.post('/user/login', form);
            // console.log('Login response:', response); // 打印后端返回的数据结构
            // this.token = response.tokenValue;
            // this.userInfo = response.user;
            // localStorage.setItem('token', response.tokenValue);

            const data  = await login(form);
            console.log('Login response.data:', data); // 打印后端返回的数据结构
            this.token = data.token.tokenValue
            this.userInfo = data.user
            localStorage.setItem('token', data.token.tokenValue)
            localStorage.setItem('userInfo', JSON.stringify(data.user))
          }catch (error) {
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            throw error
          }
        },
        async register(form: RegisterForm) {
          await register(form);
        },
        logout() {
          this.token = null
          this.userInfo = null
          localStorage.removeItem('token')
        }
      }
});